package com.kly.manager.websocket;

import com.kly.domain.entity.ChatGroup;
import com.kly.domain.entity.User;
import com.kly.manager.websocket.model.ReceiverType;
import com.kly.service.ChatGroupService;
import com.kly.service.PictureService;
import com.kly.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author admin
 * @date 2025/3/21
 */
@Slf4j
@Configuration
public class WsUserChatHandShakeInterceptor implements HandshakeInterceptor {

    @Resource
    private PictureService pictureService;

    @Resource
    private UserService userService;

    @Resource
    private ChatGroupService chatGroupService;

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        // 强转位HttpServletRequest
        if(request instanceof ServletServerHttpRequest) {
            HttpServletRequest httpServletRequest = ((ServletServerHttpRequest) request).getServletRequest();
        //     获取用户信息
            User loginUser = userService.getLoginUser(httpServletRequest);
            if (loginUser == null) {
                log.error("用户未登录");
                return false;
            }
        //     获取聊天对象id
            String roomId = httpServletRequest.getParameter("roomId");
            boolean exists = chatGroupService.lambdaQuery()
                    .eq(ChatGroup::getId, roomId)
                    .exists();
            if(exists) {
                attributes.put("receiverType", ReceiverType.GROUP.getValue());
            }

            attributes.put("roomId",Long.valueOf(roomId));
            attributes.put("loginUser",loginUser);
        }


        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

    }
}
